package com.example.zhangxin.zyfypt_124zx.model;


import com.example.zhangxin.zyfypt_124zx.bean.ArticleBean;
import com.example.zhangxin.zyfypt_124zx.iface.ArticleListener;
import com.example.zhangxin.zyfypt_124zx.iface.Articleiface;
import com.example.zhangxin.zyfypt_124zx.service.ArticleService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by zhangxin on 2017/4/19.
 */
//model,文章模块，实现Articleiface接口
public class ArticleModel implements Articleiface {
    private Retrofit retrofit;
    private String BASEURL="http://amicool.neusoft.edu.cn/";
    //构造方法
    public ArticleModel(){//访问网络    3，使用接口  1 ）创建Retrofit对象
        retrofit=new Retrofit.Builder()//创建retrofit
                .baseUrl(BASEURL) //主机地址  ↓ 直接将json数据转换成java实体类
                .addConverterFactory(GsonConverterFactory.create())//解析方法
                .build();//创建出来
        //String数据用scalars  ScalarsConverterFactory.create()


       /* Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(BASEURL);
        builder.addConverterFactory(GsonConverterFactory.create());
        retrofit=builder.build();*/
    }
    //获取文章数据
    @Override
    public void getResultList(String mod, int page, String sessionID, final ArticleListener listener) {
        //3，使用接口 2 ）创建访问API的请求 API是接口
        ArticleService articleService
                =retrofit.create(ArticleService.class);//json串转换java代码
        Call<List<ArticleBean>> call//call里有服务器返回的所有信息
                =articleService.getResult(mod,page,sessionID);

        // 3，使用接口  3 ）发送请求并处理结果
            // ↓压入队列 异步方式
        call.enqueue(new Callback<List<ArticleBean>>() {
            @Override
            public void onResponse(Call<List<ArticleBean>> call, Response<List<ArticleBean>> response) {
                if(response.isSuccessful()&&response.body()!=null)
                                            //  ↑这里是需要的结果
                    listener.onResponse(response.body());
                else
                    listener.onFail("on response fail");
            }

            @Override
            public void onFailure(Call<List<ArticleBean>> call, Throwable t) {
                listener.onFail(t.toString());
            }
        });


    }
}



